//
// Created by LiuYou on 2021/5/19.
//

#include <cstdlib>
#include <unistd.h>
#include <cstdio>
#include <pthread.h>
#include <cstring>

//static const int LEFT = 30000000;
//static const int RIGHT = 30000200;
//static int THR_NUM = RIGHT - LEFT + 1;

#define LEFT            30000000
#define RIGHT           30000200
#define THR_NUM         (RIGHT - LEFT + 1)

struct thr_arg_st {
    int n;
};

static void* thr_prime(void* pVoid);

/**
 * @brief 这个7还是有问题。:( 累了。
 */
int main() {
//    const int LEFT = 30000000;
//    const int RIGHT = 30000200;
//    int THR_NUM = RIGHT - LEFT + 1;

    pthread_t tid[THR_NUM];
    struct thr_arg_st* thrArgSt{};

    for (int i = LEFT; i <= RIGHT; ++i) {
        thrArgSt = static_cast<thr_arg_st*>(malloc(sizeof(*thrArgSt)));
        if (thrArgSt == nullptr) {
            std::perror("malloc()");
            std::exit(1);
        }
        thrArgSt->n = i;
        int err = pthread_create(tid + (i - LEFT), nullptr, thr_prime, &thrArgSt);

        if (err) {
            std::fprintf(stderr, "pthread_create(): %s\n", std::strerror(err));
            std::exit(1);
        }
    }

    void* ptr{};
    for (int i = LEFT; i <= RIGHT; ++i) {
        pthread_join(tid[i - LEFT], &ptr);
        free(ptr);
    }


    std::exit(0);
}

static void* thr_prime(void* pVoid) {
    int mark{1};

    int i = ((struct thr_arg_st*) pVoid)->n;
//    free(pVoid);

//    int i = *((int*) pVoid);
    // TODO 注意: 在C++中下面这条语句是错误的。
//    int i = (int) pVoid;

    for (int j = 2; j < i / 2; ++j) {
        if (i % j == 0) {
            mark = 0;
            break;
        }
    }
    if (mark == 1) {
        std::fprintf(stdout, "%d is prime number.\n", i);
    }

//    sleep(100);

    pthread_exit(pVoid);
}